package com.stone.tool.simpleimage;

import cn.hutool.core.io.IoUtil;
import com.alibaba.simpleimage.ImageRender;
import com.alibaba.simpleimage.render.*;
import lombok.extern.slf4j.Slf4j;

import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * https://cloud.tencent.com/developer/article/1639182
 *
 * @author stone
 * @date 2022/5/16 16:40
 */
@Slf4j
public class SimpleImageUtil {

    public static void main(String[] args) throws Exception {
//        render();
        watermark();
        log.info("执行完成 done...");
    }

    /**
     * 图片压缩：将图片压缩至100*100
     */
    public static void render() throws Exception {
        File in = new File("C:\\Users\\stone\\Desktop\\图片\\1.png");
        File out = new File("C:\\Users\\stone\\Desktop\\" + System.currentTimeMillis() + ".png");
        ScaleParameter scaleParameter = new ScaleParameter(100, 100, ScaleParameter.Algorithm.AUTO);
        WriteRender writeRender = null;
        try (
                final FileInputStream fileInputStream = new FileInputStream(in);
                final FileOutputStream fileOutputStream = new FileOutputStream(out);
        ) {
            final ReadRender render = new ReadRender(fileInputStream);
            final ScaleRender scaleRender = new ScaleRender(render, scaleParameter);
            writeRender = new WriteRender(scaleRender, fileOutputStream);
            writeRender.render();
        } finally {
            if (writeRender != null) {
                writeRender.dispose();
            }
        }
    }

    /**
     * 图片添加水印
     */
    public static void watermark() throws Exception {
        final Font font = new Font("黑体", Font.PLAIN, 20);
        FixDrawTextItem item = new FixDrawTextItem("你是人间四月天", Color.GRAY, Color.GRAY, font, 10, FixDrawTextItem.Position.CENTER, 1f);
        InputStream in = null;
        ImageRender imageRender = null;
        try {
            in = new FileInputStream("C:\\Users\\stone\\Desktop\\图片\\2.jpg");
            ImageRender readRender = new ReadRender(in);
            DrawTextParameter drawTextParameter = new DrawTextParameter();
            drawTextParameter.addTextInfo(item);
            DrawTextRender dtr = new DrawTextRender(readRender, drawTextParameter);
            imageRender = new WriteRender(dtr, "C:\\Users\\stone\\Desktop\\" + System.currentTimeMillis() + ".png");
            imageRender.render();
        } finally {
            IoUtil.close(in);
            if (imageRender != null) {
                imageRender.dispose();
            }
        }
    }

}
